package com.fragrance.service.impl;

import java.util.List;
import java.util.Map;

import com.fragrance.model.WxUserModel;
import com.fragrance.service.WeChatUserService;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class WeChatUserServiceImpl implements WeChatUserService {

	/**
	 * 保存微信用户信息
	 * */
	@Override
	public void saveWeChatUserInfo(Map<String, Object> userInfo) {
		 Record weChatUser = new Record();
		 weChatUser.set("account_no", userInfo.get("accountNo"));
		 weChatUser.set("wx_open_id", userInfo.get("openid"));
		 weChatUser.set("nick_name", userInfo.get("nickName"));
		 weChatUser.set("province", userInfo.get("province"));
		 weChatUser.set("city", userInfo.get("city"));
		 weChatUser.set("sex", userInfo.get("sex"));
		 weChatUser.set("country", userInfo.get("country"));
		 boolean existOpenid = existOpenid(userInfo.get("openid").toString());
		 if(!existOpenid){
			 Db.save("t_wx_user",weChatUser);
		 }
	}

	/**
	 * 判断是否绑定微信用户
	 * */
	@Override
	public boolean existOpenid(String openid) {
		List<WxUserModel> list = WxUserModel.me.find("select * from t_wx_user where wx_open_id = ?", openid);
		if(list!=null && list.size()==1){
			return true;
		}
		return false;
	}

	/**
	 * @param openid
	 * @return
	 */
	@Override
	public WxUserModel getWeChatUserInfo(String openid){
		List<WxUserModel> list = WxUserModel.me.find("select id, account_no, nick_name, province, city, country, sex from  t_wx_user where wx_open_id=?", openid);
		if(list!=null && list.size()==1){
			return list.get(0);
		}
		return null;
	}
	
}
